package com.incar.chuxing.activity.driving;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.R;
import com.incar.chuxing.api.RxApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.baiduMap.GeoCoderUtils;
import com.incar.chuxing.baiduMap.MapStatusUtils;
import com.incar.chuxing.baiduMap.MarkerOverlay.OverlayUtils;
import com.incar.chuxing.baiduMap.RoutePlan;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.CarInfoBean;
import com.incar.chuxing.bean.CarListBean;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class CarPositionActivity extends BaseActivity {

    @BindView(R.id.mapView)
    MapView mapView;
    private BaiduMap mBaiduMap;
    private OverlayUtils overlayUtils;
    private MapStatusUtils mapStatusUtils;

    private Context mContext = this;
    private LocationClient mLocClient;
    private MyLocationData locData;
    private LatLng curPosition;
    private LatLng carPosition;
    private String carId;

    @Override
    public int getLayoutId() {
        return R.layout.activity_car_position;
    }

    @Override
    public void initView() {
        carId = getIntent().getStringExtra("carId");


        mapView.showZoomControls(false);
        //MapView.setMapCustomEnable(true);
        if (mBaiduMap == null) {
            mBaiduMap = mapView.getMap();
            // 开启定位图层
            mBaiduMap.setBuildingsEnabled(false);
            mBaiduMap.setMyLocationEnabled(true);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, false,
                    BitmapDescriptorFactory.fromResource(R.drawable.icon_mylocation), 0x00000000, 0x00000000));
            //设置地图交互
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setOverlookingGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(true);
            curPosition = new LatLng(Double.parseDouble(((MyApplication) getApplication()).getCurPosition()[0]), Double.parseDouble(((MyApplication) getApplication()).getCurPosition()[1]));
            locData = new MyLocationData.Builder()
                    .latitude(curPosition.latitude)
                    .longitude(curPosition.longitude)
                    .build();
            mBaiduMap.setMyLocationData(locData);


            mapStatusUtils = new MapStatusUtils(mContext, mBaiduMap);
            overlayUtils = new OverlayUtils(mContext, mBaiduMap);
            mapStatusUtils.noAnimateMove(curPosition, 17);
            startLocation();

        }
    }


    private void startLocation() {
        if (mLocClient != null) {
            mLocClient.stop();
            mLocClient.unRegisterLocationListener(mListener);
            mLocClient = null;
        }
        // 定位初始化
        mLocClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(true);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        if (BuildConfig.DEBUG) {
            option.setEnableSimulateGps(true);
        }
        option.setScanSpan(8000);
        mLocClient.setLocOption(option);
        mLocClient.registerLocationListener(mListener);
        if (null != mLocClient) mLocClient.restart();
        updateCarDetail();

    }


    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation != null)
                if (!BuildConfig.DEBUG) {
                    curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                } else {
                    switch (SPUtils.getInstance(mContext).getIntValue("$s_locationMode")) {
                        case 0:
                        case 1:
                            curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                            break;
                        case 2:
                            curPosition = new LatLng(Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude")),
                                    Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude")));// 更新定位
                            break;
                    }
                }
            locData = new MyLocationData.Builder()
                    .latitude(curPosition.latitude)
                    .longitude(curPosition.longitude)
                    .build();
            mBaiduMap.setMyLocationData(locData);
        }
    };


    private void updateCarDetail() {
        showLoadingDialog();
        //更新车的信息
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getCarInfo(((MyApplication) getApplication()).getRequestFieldMap(), carId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<CarInfoBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CarInfoBean carInfoBean) {
                if (carInfoBean != null && carInfoBean.getStatus() == 200 && carInfoBean.getAttachment() != null) {
                    dismissLoadingDialog();
                    //展示选中的车详情
                    carPosition = new LatLng(carInfoBean.getAttachment().getLatitude(), carInfoBean.getAttachment().getLongitude());
                    RoutePlan.getInstance().clearRoutePlanning();
                    RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition, carPosition, null);
                    CarListBean.AttachmentBean.ContentBean carBean = new CarListBean.AttachmentBean.ContentBean();
                    carBean.setLatitude(carPosition.latitude);
                    carBean.setLongitude(carPosition.longitude);

                    //更新这个车的Marker信息
                    View view = View.inflate(mContext, R.layout.car_marker_selected, null);
                    ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
                    imageView.setImageResource(R.drawable.car_marker);
                    mBaiduMap.addOverlay(new MarkerOptions()
                            .position(carPosition)
                            .icon(BitmapDescriptorFactory.fromView(view)));
                    GeoCoderUtils.getInstance().reverseGeoCode(carPosition, new GeoCoderUtils.OnGeoListener() {
                        @Override
                        public void onGeoSuccess(String address, String cityCode, String city, String adCode) {
                            carBean.setRemarkMsg(address);
                            overlayUtils.showFindCarInfoWindow(carBean, 1);
                        }

                        @Override
                        public void onGeoFailure() {

                        }
                    });
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();

            }

            @Override
            public void onComplete() {

            }
        });

    }


    @OnClick({R.id.title_back, R.id.imageView_locate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.imageView_locate:
                mapStatusUtils.animateMove(curPosition, 17, 400);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (mLocClient != null) {
            mLocClient.stop();
            mLocClient.unRegisterLocationListener(mListener);
            mLocClient = null;
        }
        super.onDestroy();
    }
}
